{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Net(\n",
      "  (conv1): Conv2d(1, 6, kernel_size=(3, 3), stride=(1, 1))\n",
      "  (conv2): Conv2d(6, 16, kernel_size=(3, 3), stride=(1, 1))\n",
      "  (fc1): Linear(in_features=576, out_features=120, bias=True)\n",
      "  (fc2): Linear(in_features=120, out_features=84, bias=True)\n",
      "  (fc3): Linear(in_features=84, out_features=10, bias=True)\n",
      ")\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "\n",
    "class Net(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(Net,self).__init__()\n",
    "        self.conv1 = nn.Conv2d(1,6,3)\n",
    "        self.conv2 = nn.Conv2d(6,16,3)\n",
    "        self.fc1 = nn.Linear(16*6*6,120)\n",
    "        self.fc2 = nn.Linear(120,84)\n",
    "        self.fc3 = nn.Linear(84,10)\n",
    "        \n",
    "    def forward(self,x):\n",
    "        x = F.max_pool2d(F.relu(self.conv1(x)),(2,2))\n",
    "        x = F.max_pool2d(F.relu(self.conv2(x)),2)\n",
    "        x = x.view(-1,self.num_flat_features(x))\n",
    "        x = F.relu(self.fc1(x))\n",
    "        x = F.relu(self.fc2(x))\n",
    "        x = self.fc3(x)\n",
    "        return x\n",
    "    \n",
    "    def num_flat_features(self,x):\n",
    "        size = x.size()[1:] # all dimensions except the batch dimension\n",
    "        num_flat_features = 1\n",
    "        for s in size:\n",
    "            num_flat_features *= s\n",
    "        return num_flat_features\n",
    "\n",
    "net = Net()\n",
    "print(net)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "10\n",
      "torch.Size([6, 1, 3, 3])\n"
     ]
    }
   ],
   "source": [
    "params = list(net.parameters())\n",
    "print(len(params))\n",
    "print(params[0].size())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor([[-0.0227, -0.0831,  0.0139,  0.0710, -0.0259,  0.0112,  0.0730, -0.0054,\n",
      "         -0.0789, -0.0081]], grad_fn=<AddmmBackward0>)\n"
     ]
    }
   ],
   "source": [
    "input= torch.randn(1,1,32,32)\n",
    "out = net(input)\n",
    "print(out)"
   ]
  },
  {
   "cell_type": "raw",
   "metadata": {},
   "source": [
    "net.zero_grad()\n",
    "out.backward(torch.randn(1,10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "tensor(0.8125, grad_fn=<MseLossBackward0>)\n"
     ]
    }
   ],
   "source": [
    "output = net(input)\n",
    "target = torch.randn(10)\n",
    "target = target.view(1,-1)\n",
    "criterion = nn.MSELoss()\n",
    "\n",
    "loss = criterion(output,target)\n",
    "print(loss)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<MseLossBackward0 object at 0x7f8ee017fe20>\n",
      "<AddmmBackward0 object at 0x7f8ee017f580>\n",
      "<AccumulateGrad object at 0x7f8ee017fe20>\n"
     ]
    }
   ],
   "source": [
    "print(loss.grad_fn) # MSELoss\n",
    "print(loss.grad_fn.next_functions[0][0]) # Linear\n",
    "print(loss.grad_fn.next_functions[0][0].next_functions[0][0]) # ReLu"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "conv1.bias.grad before backward\n",
      "None\n",
      "conv1.bias.grad after backward\n",
      "tensor([ 0.0021, -0.0017, -0.0029,  0.0101, -0.0004,  0.0165])\n"
     ]
    }
   ],
   "source": [
    "net.zero_grad()\n",
    "\n",
    "print('conv1.bias.grad before backward')\n",
    "print(net.conv1.bias.grad)\n",
    "\n",
    "loss.backward()\n",
    "\n",
    "print('conv1.bias.grad after backward')\n",
    "print(net.conv1.bias.grad)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### update the weights"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "learning_rate = 0.01\n",
    "for f in net.parameters():\n",
    "    f.data.sub_(f.grad.data *learning_rate)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch.optim as optim\n",
    "\n",
    "optimizer = optim.SGD(net.parameters(),lr=0.01)\n",
    "\n",
    "optimizer.zero_grad()\n",
    "output = net(input)\n",
    "loss = criterion(output,target)\n",
    "loss.backward()\n",
    "optimizer.step()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
